# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.00
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

### Channel operator management

from time import sleep
from flask import Blueprint
from flask import request
import utils.wraps.urlcost as urlcost
import utils.wraps.token as token
import utils.message.response as response
import utils.pgsql.pgoperator
import utils.pgsql.pgcase
import utils.pgsql.pgdevice
import utils.pgsql.pgadmin
import utils.wraps.token
import json
import requests




operator_module = Blueprint("operator", __name__, url_prefix="/api/v1/account/operator")


@operator_module.route("/", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def operator_add():
   
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    print("userInfo",userInfo)
    if userInfo["role"] == 1:
        obj = utils.pgsql.pgoperator.PgOperator()
        operatorInfo = json.loads(request.data)
        print("operatorInfo",operatorInfo)

        res = obj.addOperator(operatorInfo)
        print("res",res)
        if res == {}:
            return response.make_response_1505()
        return response.make_response_success(res)
    else:
        return response.make_response_401()

# 2.获取当前操作员（运营商）的信息
@operator_module.route("/", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def operator_all():
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    # print("userInfo",userInfo)
    if userInfo["role"] == 1:
        obj = utils.pgsql.pgoperator.PgOperator()
        res = obj.all()
        # print("运营商：",res)
        if res == "":

            return response.make_response_1505()
        return response.make_response_success(res)
    else:
        return response.make_response_401()


 
@operator_module.route("/operatorall", methods=["GET"])
@urlcost.cost_count_wraps
def operator_tech_all():
 

    obj = utils.pgsql.pgoperator.PgOperator()
    res = obj.all()
    if(res):
        return response.make_response_success(res)
    else:
        return response.make_response_1000()

@operator_module.route("/<int:operatorId>", methods=["PUT"])
@token.login_required
@urlcost.cost_count_wraps
def operatorId_put(operatorId):
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    if userInfo["role"] in [1, 2, 3]:
        obj = utils.pgsql.pgoperator.PgOperator()
        dic = json.loads(request.data)
        if obj.modify(dic, "operatorId", operatorId):
            return response.make_response_success_no_data()
        else:
            return response.make_response_1505()
    else:
        return response.make_response_401()


@operator_module.route("/unused", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def operator_id():
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] == 1:
        obj = utils.pgsql.pgoperator.PgOperator()
        res = obj.getUnusedOperator()
        if res == "":
            return response.make_response_1505()
        return response.make_response_success(res)
    else:
        return response.make_response_401()


@operator_module.route("/<int:operatorId>", methods=["DELETE"])
@token.login_required
@urlcost.cost_count_wraps
def operator_delete(operatorId):
     
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] == 1 and (operatorId not in [1]):  ## 1 : shuikewenhua  forbbiden deletion
        obj = utils.pgsql.pgoperator.PgOperator()
        obj.getoperatornamer(operatorId)
        obj_case = utils.pgsql.pgcase.PgCase()
        caselist = obj_case.allByOperator(operatorId)
        for i in range(len(caselist)):
            obj_case.soft_delete(caselist[i]["caseId"], caselist[i]["caseName"])
        if obj.soft_delete(
            operatorId, obj.getoperatornamer(operatorId)["operatorName"]
        ):   
            adminobj = utils.pgsql.pgadmin.PgAdmin()
            adminobj.operatordelete(operatorId)

            deviceobj = utils.pgsql.pgdevice.PgDevice()
            devicedeletes = deviceobj.allByOperator_streamType(
                operatorId
            )   
            devicedelete = []
            for i in devicedeletes:
                if i not in devicedelete:
                    devicedelete.append(i)   
            allstreamType = deviceobj.allstreamType()  
            for i in devicedelete:   
                if i not in allstreamType:
                    url = "http://127.0.0.1:33033/api/v1/scenic/device/delete"
                    header = {
                        "content-type": "application/json",
                        "Authorization": "ZTAI5t7StH4JsKGysZfb2XgT",
                    }
                    res = requests.post(
                        url,
                        json.dumps(
                            {
                                "deviceIp": i["deviceIp"],
                                "deviceAiboxId": i["deviceAiboxId"],
                            }
                        ),
                        headers=header,
                        timeout=5,
                    )
            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    elif operatorId in [1, 2]:
        return response.make_response_error_1500()
    else:
        return response.make_response_401()
